import { defineComponent, h } from "vue";
import { GLOBAL_KEY as langKey } from "./i18n"
import {get} from "lodash-es"

// {label,icon,url,}
export const UIMenuItem = defineComponent((props, ctx) => {
    const { item,handle } = props;
    const slots = ctx.slots;
    const temp: any = slots.default
    const { icon, label, url, title = '' } = item;
    const lang = (window as any)?.[langKey]
    const isImg = icon && (/^http/.test(icon) || /\.(jpg|png|jpeg|gif|ico)$/.test(icon) || /^data:image/.test(icon));

    const handleClick = (item:any) => {
        // URL
        // event call
        if(handle &&  typeof handle == 'function'){handle(item)}
        else {
            
        }
    }
    // console.log(slots,temp())
    return () => h('div', { class: `ui-menu-item ${item.children ? 'ui-menu-item-sub' : ''}` }, [
        temp ? temp({item,onclick:() => handleClick(item)}) : h('div', { class: "ui-menu-item--title", title, onClick: () => handleClick(item) }, [
            icon ? isImg ? h('img', { src: icon }) : h('div', { class: icon },) : '',
            label ? h('div', {}, lang ? lang.t(label) : label) : ''
        ]), item.children ? item.children.map((t: any) => h(UIMenuItem, { item: t ,handle}))
            : '']
    )
}, { props: ['item','handle'] })

export const UIMenu = defineComponent((props, ctx) => {
    const { menus = [],handle } = props;
    // console.log(ctx.slots, ctx.slots.default)
    return () => h('div', { class: "ui-menu" }, menus.map((item: any) => h(UIMenuItem, { item ,handle}, ctx.slots)))
}, { props: ['menus','handle'] })


interface Props {
    label?:string
    icon?:string
    children?:string
    link?:string
}

export namespace Menu {

    // 菜单树 数据转换
    export const transform = (tree:any[],props:Props = {},filter:(item:any) => boolean = () => true) => {
        const ks = Object.assign({label:'label',icon:'icon',children:'children',link:'link'},props)
        const {label,icon,children,link} = ks;
    
        const loop = (td:any[]) => {
            const res:any[] = [];
            for(const d of td){
                if(!filter(d)){continue;}
                const o:any = {label:get(d,label),icon:get(d,icon),link:get(d,link),source:d}
                if(d[children] && Array.isArray(d[children])){
                    o.children = loop(d[children])
                }
                res.push(d)
            }
            return res;
        }
        return loop(tree)
    }
}